package com.cincc.cinccimdemo.widget;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.adapter.EmojiAdapter;
import com.cincc.cinccimdemo.common.AttrConstants;
import com.cincc.cinccimdemo.common.DisplayUtils;
import com.cincc.cinccimdemo.common.EmojiUtils;
import com.cincc.cinccimdemo.common.FileUtils;
import com.cincc.cinccimdemo.common.MyUtils;
import com.cincc.cinccimdemo.model.ConversationInfo;
import com.cincc.cinccimdemo.model.MessageInfo;
import com.cincc.cinccimdemo.model.MessageInfoUI;
import com.cincc.cinccimdemo.ui.conversation.card.PickUserActivity;
import com.cincc.cinccimdemo.ui.conversation.mm.TakePhotoActivity;
import com.cincc.cinccimdemo.ui.conversation.sequence.SequenceActivity;
import com.cincc.cinccimdemo.viewmodel.ConversationViewModel;
import com.cincc.im.callback.ImCallback;
import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.model.ImMessageInfo;
import com.cincc.im.model.ImResponse;
import com.cincc.im.model.enums.ImSendType;
import com.cincc.im.model.enums.SendStatus;
import com.cincc.im.model.message.ImVideoMessage;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;

import java.util.ArrayList;
import java.util.List;

public class ConversationMoreLayout extends FrameLayout implements View.OnClickListener {
    public static final int FILE_REQUEST_CODE = 10005;
    public static final int CAMERA_REQUEST_CODE = 10004;
    public static final int PERMISSIONS_REQUEST_CALL_CAMERA = 1002;
    private static final String TAG = "ConversationMoreLayout";
    Activity mContext;
    ConversationViewModel conversationViewModel;
    int spanCount = 8;
    EditText editText;
    ConversationInfo conversationInfo;

    public ConversationMoreLayout(@NonNull Context context) {
        super(context);
        init(context);
    }

    public ConversationMoreLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ConversationMoreLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    RecyclerView emojiRecycler;

    private void init(Context context) {
        mContext = (Activity) context;
        EmojiUtils.loadEmoji();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.conversation_more, this);

        RelativeLayout albumLayout = findViewById(R.id.album_rl);
        albumLayout.setOnClickListener(this);
        RelativeLayout cameraLayout = findViewById(R.id.camera_rl);
        cameraLayout.setOnClickListener(this);
        RelativeLayout fileLayout = findViewById(R.id.file_rl);
        fileLayout.setOnClickListener(this);
        RelativeLayout sequenceLayout = findViewById(R.id.sequence_rl);
        sequenceLayout.setOnClickListener(this);

        RelativeLayout cardLayout = findViewById(R.id.card_rl);
        cardLayout.setOnClickListener(this);

        LinearLayout containerLayout = findViewById(R.id.ll_container);
        ConstraintLayout delLayout = findViewById(R.id.del_layout);
        delLayout.setOnClickListener(this);
        emojiRecycler = findViewById(R.id.emoji_recycler);
        emojiRecycler.setLayoutManager(new GridLayoutManager(mContext, spanCount));

        View tabView = inflater.inflate(R.layout.emoji_tab_item, null);
        ImageView imageView = tabView.findViewById(R.id.emoji_tab_img);
        imageView.setImageResource(R.mipmap.ic_emoji);
        containerLayout.addView(tabView);

        this.post(this::initEmoji);
    }

    private void initEmoji() {
        List<Bitmap> bitmaps = EmojiUtils.getmDrawableCache();
        EmojiAdapter emojiAdapter = new EmojiAdapter(mContext, bitmaps);
        int itemWidth = DisplayUtils.dip2px(mContext, 40);

        int space = (DisplayUtils.getScreenWidth(mContext) - itemWidth * spanCount) / (spanCount);
        emojiRecycler.addItemDecoration(new SpaceItemDecoration(space));
        emojiRecycler.setAdapter(emojiAdapter);
        emojiAdapter.setOnItemClickListener(index -> {
            String name = EmojiUtils.getName(index);
            int curPosition = editText.getSelectionStart();
            StringBuilder sb = new StringBuilder(editText.getText().toString());
            sb.insert(curPosition, name);
            SpannableString spannableString = EmojiUtils.text2Emoji(mContext,
                    sb.toString(), editText.getTextSize());
            editText.setText(spannableString);
            editText.setSelection(curPosition + name.length());
        });
    }

    public void setEditText(EditText editText) {
        this.editText = editText;
    }

    public void setContent(boolean isEmoji) {
        LinearLayout normalLayout = findViewById(R.id.layout_more);
        ConstraintLayout emojiLayout = findViewById(R.id.layout_emoji);
        normalLayout.setVisibility(isEmoji ? GONE : VISIBLE);
        emojiLayout.setVisibility(isEmoji ? VISIBLE : GONE);
    }

    public void hideContent() {
        LinearLayout normalLayout = findViewById(R.id.layout_more);
        ConstraintLayout emojiLayout = findViewById(R.id.layout_emoji);
        normalLayout.setVisibility(GONE);
        emojiLayout.setVisibility(GONE);
    }

    public int emojiIsShow() {
        ConstraintLayout emojiLayout = findViewById(R.id.layout_emoji);
        return emojiLayout.getVisibility();
    }

    public int moreIsShow() {
        LinearLayout normalLayout = findViewById(R.id.layout_more);
        return normalLayout.getVisibility();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.album_rl) {
            sendAlbumImage();
        } else if (v.getId() == R.id.camera_rl) {
            sendCameraImage();
        } else if (v.getId() == R.id.file_rl) {
            openFilePicker();
        } else if (v.getId() == R.id.del_layout) {
            delete();
        } else if (v.getId() == R.id.sequence_rl) {
            startSequence();
        } else if (v.getId() == R.id.card_rl) {
            startPickUser();
        }
    }

    private void delete() {
        editText.dispatchKeyEvent(new KeyEvent(
                KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//无类型限制
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        mContext.startActivityForResult(intent, FILE_REQUEST_CODE);
    }

    private void startSequence() {
        Intent i = new Intent(mContext, SequenceActivity.class);
        i.putExtra(AttrConstants.GROUP_ID, conversationInfo.targetId);
        i.putExtra(AttrConstants.IS_CREATE_SEQUENCE, true);
        mContext.startActivity(i);
    }

    private void startPickUser() {
        Intent i = new Intent(mContext, PickUserActivity.class);
        mContext.startActivity(i);
    }

    /**
     * 发送相册图片消息
     */
    private void sendAlbumImage() {
        applyPermission();
    }

    int REQUEST_CODE_SCAN_QR_CODE = 1207;
    int REQUEST_CODE_IMAGE = 9092;

    private void applyPermission() {
        String[] permissions = new String[1];

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
                getTargetSdkVersion() >= Build.VERSION_CODES.TIRAMISU) {
            permissions[0] = Manifest.permission.READ_MEDIA_IMAGES;
        } else {
            permissions[0] = Manifest.permission.READ_EXTERNAL_STORAGE;
        }
        if (!checkPermission(permissions)) {
            mContext.requestPermissions(permissions, REQUEST_CODE_SCAN_QR_CODE);
        } else {
            Intent intent = ImagePicker.picker().showCamera(false).buildPickIntent(mContext);
            mContext.startActivityForResult(intent, REQUEST_CODE_IMAGE);
        }
    }

    private int getTargetSdkVersion() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(mContext.getPackageName(), 0);
            return applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1; // 获取失败时返回-1或其他适当的值
        }
    }

    /**
     * 发送拍照图片消息
     */
    private void sendCameraImage() {
        if (mContext.checkCallingOrSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            mContext.requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CALL_CAMERA);
        } else {
            takePhoto();
        }
    }

    /**
     * 拍照的方法
     */
    private void takePhoto() {
        Intent intent = new Intent(mContext, TakePhotoActivity.class);
        mContext.startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    public void setConversationModel(ConversationViewModel p2PConversationViewModel, ConversationInfo conversationInfo) {
        this.conversationViewModel = p2PConversationViewModel;
        this.conversationInfo = conversationInfo;

        findViewById(R.id.sequence_rl).setVisibility(ImSendType.isP2P(conversationInfo.imSendType) ? INVISIBLE : VISIBLE);
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE && data != null) {
            //处理从相册返回的结果
            String path = data.getStringExtra("path");
            if (TextUtils.isEmpty(path)) {
                Toast.makeText(mContext, "拍照错误, 请向我们反馈", Toast.LENGTH_SHORT).show();
                return;
            }
            if (data.getBooleanExtra("take_photo", true)) {
                //照片
                sendImage(path);
            } else {
                //小视频

            }
        } else if (requestCode == FILE_REQUEST_CODE && data != null) {
            //处理从文件管理器选择了一个文件的结果
            String path = FileUtils.getPath(mContext, data.getData());
            pickerFile(path);
        } else if (requestCode == REQUEST_CODE_IMAGE && data != null) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            for (ImageItem imageItem : images) {
                try {
                    sendImage(imageItem.path);
                } catch (Exception e) {
                    Log.e(TAG, "onActivityResult: " + e.getMessage());
                }
            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_CALL_CAMERA) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
                MyUtils.showToast(mContext, mContext.getString(R.string.request_take_photo_tips));
            }
        }
    }

    private void sendImage(String imagePath) {
        MessageInfo textMessage = MyUtils.getImageMessageInfo(imagePath, conversationInfo.imSendType);
        MessageInfoUI uiMessage = new MessageInfoUI(textMessage);
        conversationViewModel.conversationLiveData().postValue(uiMessage);
        IMSipPhoneCtrl.getInstance().sendImage(conversationInfo.imSendType, conversationInfo.targetId, imagePath, "", new ImCallback() {
            @Override
            public void callback(ImResponse imResponse) {
                if (imResponse.getCode() == 0) {
                    ImMessageInfo imMessageInfo = (ImMessageInfo) imResponse.getData();
                    uiMessage.setRemoteMsgId(imMessageInfo.msgId);
                }
                uiMessage.setMessageStatus(imResponse.getCode() == 0 ? SendStatus.SEND_SUCCESS : SendStatus.SEND_FAILED);
                conversationViewModel.updateConversationLiveData().postValue(uiMessage);
            }
        });
    }

    private void sendVideo(String videoPath) {
        MessageInfo textMessage = MyUtils.getVideoMessageInfo(videoPath, conversationInfo.imSendType);
        MessageInfoUI uiMessage = new MessageInfoUI(textMessage);
        conversationViewModel.conversationLiveData().postValue(uiMessage);
        IMSipPhoneCtrl.getInstance().sendVideo(conversationInfo.imSendType, conversationInfo.targetId, videoPath, "", new ImCallback() {
            @Override
            public void callback(ImResponse imResponse) {
                if (imResponse.getCode() == 0) {
                    ImMessageInfo imMessageInfo = (ImMessageInfo) imResponse.getData();
                    uiMessage.setRemoteMsgId(imMessageInfo.msgId);

                    ImVideoMessage videoMessage = (ImVideoMessage) uiMessage.getMessageInfo().imMessage;
                    videoMessage.thumb = imMessageInfo.thumb;
                    uiMessage.getMessageInfo().imMessage = videoMessage;
                }
                uiMessage.setMessageStatus(imResponse.getCode() == 0 ? SendStatus.SEND_SUCCESS : SendStatus.SEND_FAILED);
                conversationViewModel.updateConversationLiveData().postValue(uiMessage);
            }
        });
    }

    private void sendFile(String filePath) {
        MessageInfo textMessage = MyUtils.getFileMessageInfo(filePath, conversationInfo.imSendType);
        MessageInfoUI uiMessage = new MessageInfoUI(textMessage);
        conversationViewModel.conversationLiveData().postValue(uiMessage);
        IMSipPhoneCtrl.getInstance().sendFile(conversationInfo.imSendType, conversationInfo.targetId, filePath, "", new ImCallback() {
            @Override
            public void callback(ImResponse imResponse) {
                if (imResponse.getCode() == 0) {
                    ImMessageInfo imMessageInfo = (ImMessageInfo) imResponse.getData();
                    uiMessage.setRemoteMsgId(imMessageInfo.msgId);
                }
                uiMessage.setMessageStatus(imResponse.getCode() == 0 ? SendStatus.SEND_SUCCESS : SendStatus.SEND_FAILED);
                conversationViewModel.updateConversationLiveData().postValue(uiMessage);
            }
        });
    }


    private void pickerFile(String path) {
        String type = path.substring(path.lastIndexOf("."));
        switch (type) {
            case ".png":
            case ".jpg":
            case ".jpeg":
            case ".gif":
                sendImage(path);
                break;
            case ".3gp":
            case ".mpg":
            case ".mpeg":
            case ".mpe":
            case ".mp4":
            case ".avi":
                sendVideo(path);
                break;
            default:
                sendFile(path);
                break;
        }
    }

    public boolean checkPermission(String[] permissions) {
        boolean granted = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                granted = mContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                if (!granted) {
                    break;
                }
            }
        }
        return granted;
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            //不是第一个的格子都设一个左边和底部的间距
            outRect.top = space;
//            if (parent.getChildLayoutPosition(view) % spanCount == 0) {
//                outRect.left = 0;
//                outRect.right = space / 2;
//            } else if ((parent.getChildAdapterPosition(view) + 1) % spanCount == 0) {
//                outRect.left = space / 2;
//                outRect.right = 0;
//            } else {
//                outRect.left = space;
//                outRect.right = space;
//            }

            outRect.left = space / 2;
            outRect.right = space / 2;
            int lie = parent.getChildLayoutPosition(view) % spanCount;
            System.out.println("当前列 = " + lie + " left = " + outRect.left + " right = " + outRect.right);

////            if ((parent.getChildAdapterPosition(view) + 1) % spanCount == 0) {
////                System.out.println("item index = " + parent.getChildAdapterPosition(view));
////                outRect.right = space;
////            }
//            if (parent.getChildAdapterPosition(view) < spanCount) {
//                outRect.top = space;
//            }
        }

    }
}
